<template>
  <!--外部容器-->
  <div class="container">
    <!--筛选容器-->
    <div class="filter-container">
      <!-- 本科/大专/全部三选一筛选-->
      <div class="school-container filter-item">
        <h2 for="school-type" class="school-label">办学层次：</h2>
        <div class="school-type">
          <input type="radio" id="undergraduate" name="educationLevel" value="本科" @change="updateEducationLevel('本科')"
            :checked="selectedEducationLevel === '本科'">
          <label for="undergraduate">本科</label>
          <input type="radio" id="junior" name="educationLevel" value="专科" @change="updateEducationLevel('专科')"
            :checked="selectedEducationLevel === '专科'">
          <label for="junior">专科</label>
          <input type="radio" id="allschool" name="educationLevel" value="所有" @change="updateEducationLevel('所有')"
            :checked="selectedEducationLevel === '所有'">
          <label for="allschool">所有</label>
        </div>
      </div>
      <!-- 省份选择（搜索框 + 下拉菜单） -->
      <div class="city-select filter-item">
        <input type="text" list="province-list" placeholder="搜索省份..." @input="checkProvinceType($event.target.value)"
          @change="checkProvinceType($event.target.value)" v-model="selectedProvince" />
        <datalist id="province-list">
          <option value="北京市"></option>
          <option value="上海市"></option>
          <option value="天津市"></option>
          <option value="重庆市"></option>
          <option value="河北省"></option>
          <option value="山西省"></option>
          <option value="内蒙古自治区"></option>
          <option value="辽宁省"></option>
          <option value="吉林省"></option>
          <option value="黑龙江省"></option>
          <option value="江苏省"></option>
          <option value="浙江省"></option>
          <option value="安徽省"></option>
          <option value="福建省"></option>
          <option value="江西省"></option>
          <option value="山东省"></option>
          <option value="河南省"></option>
          <option value="湖北省"></option>
          <option value="湖南省"></option>
          <option value="广东省"></option>
          <option value="广西壮族自治区"></option>
          <option value="海南省"></option>
          <option value="四川省"></option>
          <option value="贵州省"></option>
          <option value="云南省"></option>
          <option value="西藏自治区"></option>
          <option value="陕西省"></option>
          <option value="甘肃省"></option>
          <option value="青海省"></option>
          <option value="宁夏回族自治区"></option>
          <option value="新疆维吾尔自治区"></option>
          <option value="香港特别行政区"></option>
          <option value="澳门特别行政区"></option>
          <option value="台湾省"></option>
        </datalist>
      </div>
      <!-- 市级行政区选择（当省份非直辖市时显示） -->
      <div class="filter-item">
        <div id="city-select" class="city-select" hidden>
          <input type="text" list="city-list" placeholder="搜索市级行政区..." v-model="selectedCity" />
          <datalist id="city-list">
            <option v-for="city in cityOptions" :key="city" :value="city"></option>
          </datalist>
        </div>
      </div>
    </div>
    <!-- 搜索框-->
    <div class="search-box">
      <input type="text" placeholder="输入关键字，搜索大学相关信息..." class="search-input" v-model="searchQuery"
        @keyup.enter="handleSearch()" @focus="showDropdown = true" @blur="hidenDropdownTemp()" />
      <button class="search-btn" @click="handleSearch()">搜索</button>

      <!-- 下拉菜单显示搜索结果 -->
      <div v-if="searchResults.length > 0 && showDropdown" class="search-dropdown">
        <div v-for="(item, index) in searchResults" :key="item.id" class="dropdown-item" @mousedown="selectItem(item)">
          <div class="item-title">{{ item.name }}</div>
        </div>
      </div>
    </div>

    <!-- 输出列表 -->
    <div class="search-results" v-if="searchResults.length > 0">
      <table class="results-table">
        <thead>
          <tr>
            <th style="width: 8%;">序号</th>
            <th style="width: 20%;">学校名称</th>
            <th style="width: 12%;">学校标识码</th>
            <th style="width: 15%;">主管部门</th>
            <th style="width: 12%;">所在地</th>
            <th style="width: 10%;">办学层次</th>
            <th style="width: 13%;">备注</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in searchResults" :key="item.id" class="table-row">
            <td style="width: 8%;">{{ item.id }}</td>
            <td style="width: 20%;">{{ item.name }}</td>
            <td style="width: 12%;">{{ item.code }}</td>
            <td style="width: 15%;">{{ item.department }}</td>
            <td style="width: 12%;">{{ item.city }}</td>
            <td style="width: 10%;">{{ item.education_level }}</td>
            <td style="width: 13%;">{{ item.remark }}</td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import provinceCityMap from './assets/data/province-city-map.json'

// 搜索相关的响应式数据
const searchQuery = ref('')
const selectedEducationLevel = ref('所有')
const selectedProvince = ref('')
const selectedCity = ref('')

// 添加控制下拉菜单显示的响应式变量
const showDropdown = ref(false)

//响应式的市级行政区选项
const cityOptions = ref<string[]>([])
const searchResults = ref<any[]>([])

// 更新学历选择
const updateEducationLevel = (level: string) => {
  selectedEducationLevel.value = level
}

//修改市级行政区选择的显示状态，并且传递省份下市级行政区列表参数
const checkProvinceType = (province: string) => {
  selectedProvince.value = province;
  console.log(province);
  // 检查是否包含"省"或"自治区"（需要显示市级选择）
  if (province.includes('省') || province.includes('自治区')) {
    document.getElementById('city-select')?.removeAttribute('hidden');
    if (province in provinceCityMap) {
      cityOptions.value = provinceCityMap[province as keyof typeof provinceCityMap];
    } else {
      cityOptions.value = [];
    }
  } else {
    // 其他情况隐藏
    document.getElementById('city-select')?.setAttribute('hidden', '');
  }
}

//搜索功能
const handleSearch = async () => {
  const searchParams = {
    keyword: searchQuery.value,
    educationLevel: selectedEducationLevel.value,
    province: selectedProvince.value,
    city: selectedCity.value
  }
  console.log('搜索参数:', searchParams)
  try {
    const response = await fetch('api/search', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify(searchParams)
    })
    if (response.ok) {
      const data = await response.json()
      console.log('搜索结果:', data)
      searchResults.value = data[0].data || []
    } else {
      console.error('搜索失败:', response.status)
    }
  } catch (error) {
    console.error('搜索失败:', error);
  }
  //搜索之后要把城市参数的搜索参数清空
  selectedCity.value = '';
  selectedProvince.value = '';
  // 这里可以调用API进行搜索
}

// 添加点击选项后隐藏下拉菜单的方法
const hidenDropdownTemp = () => {
  // 延迟隐藏，确保点击选项时能正常触发
  setTimeout(() => {
    showDropdown.value = false
  }, 200)
}

//跳转选项
const selectItem = (item: any) => {
  searchQuery.value = item.name
  showDropdown.value = false
  // 可以在这里添加跳转到详情页或其他操作
}
</script>

<style scoped>
/* 外部容器的宽度 */
.container {
  width: 1200px;
  height: 800px;
  padding: 0px 20px 20px 20px;
  top: 20px;
  margin-top: 0 !important;
  /*确保无顶部外边距*/
}

.filter-container {
  top: 0;
  z-index: 2;
  padding-top: 10px;
  padding-bottom: 15px;
  display: flex;
  gap: 10px;
  justify-content: flex-start;
  width: 100%;
  /*继承父容器的宽度*/
}

.filter-item {
  flex: 1;
}

/* 省份和市级行政区搜索框样式 */
.city-select input {
  width: 80%;
  padding: 24px 30px;
  /* 左侧留出空间，右侧为三角留空间 */
  border: 1px solid #ddd;
  border-radius: 7.5px;
  /* 圆角矩形 */
  outline: none;
  transition: all 0.3s ease;
  font-size: 20px;
}

.city-select input:focus {
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.school-container {
  width: 100%;
}

.school-label {
  display: block;
  text-align: left;
}

.school-type {
  display: flex;
  gap: 20px;
  align-items: center;
}

.school-type input[type="radio"] {
  display: none;
}

.school-type label {
  padding: 12px 24px;
  border: 2px solid #ddd;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  font-weight: 500;
  transition: all 0.3s ease;
  background-color: #fff;
  color: #333;
}

/* 选中状态为绿色 */
.school-type input[type="radio"]:checked+label {
  background-color: #4CAF50;
  color: white;
  border-color: #4CAF50;
  box-shadow: 0 4px 8px rgba(76, 175, 80, 0.2);
}

.school-type label:hover {
  background-color: #f5f5f5;
  border-color: #4CAF50;
}

.school-type input[type="radio"]:checked+label:hover {
  background-color: #45a049;
}

.search-box {
  margin-top: 60px;
  /* 添加与筛选容器的间距 */
  display: flex;
  gap: 10px;
  align-items: center;
  position: relative;
}

.search-input {
  flex: 1;
  padding: 15px 20px;
  border: 2px solid #ddd;
  border-radius: 25px;
  /* 圆角 */
  font-size: 16px;
  outline: none;
  transition: all 0.3s ease;
}

.search-input:focus {
  border-color: #4CAF50;
  box-shadow: 0 0 0 2px rgba(76, 175, 80, 0.2);
}

.search-btn {
  padding: 15px 30px;
  border: none;
  border-radius: 25px;
  /* 圆角 */
  background-color: #4CAF50;
  color: white;
  font-size: 16px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.search-btn:hover {
  background-color: #45a049;
}

.search-dropdown-container {
  position: relative;
  width: 100%;
}

.search-dropdown {
  position: absolute;
  z-index: 4;
  top: 100%;
  left: 0;
  right: 0;
  background: white;
  border: 1px solid #ddd;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  max-height: 300px;
  overflow-y: auto;
  margin-top: 5px;
}

.dropdown-item {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
  cursor: pointer;
  text-align: left;
}

.dropdown-item:hover {
  background-color: #f5f5f5;
}

.dropdown-item:last-child {
  border-bottom: none;
}

.item-title {
  font-weight: 500;
  color: #333;
  text-align: left;
}

.item-details {
  font-size: 14px;
  color: #666;
  margin-top: 4px;
}

.search-results {
  margin-top: 30px;
  width: 100%;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.results-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.results-table thead {
  background-color: #4CAF50;
  color: white;
}

.results-table th {
  padding: 12px 15px;
  text-align: left;
  font-weight: 600;
  border-bottom: 2px solid #45a049;
}

.results-table td {
  padding: 12px 15px;
  border-bottom: 1px solid #eee;
}

.results-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.results-table tbody tr:hover {
  background-color: #f5f5f5;
  transition: background-color 0.2s ease;
}

.table-row {
  cursor: pointer;
}

.table-row:hover {
  background-color: #e8f5e9 !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .results-table {
    font-size: 12px;
  }

  .results-table th,
  .results-table td {
    padding: 8px 10px;
  }
}

@media (max-width: 768px) {
  .search-results {
    overflow-x: auto;
  }

  .results-table {
    min-width: 600px;
  }
}
</style>
